<?php

defined('SYSPATH') or die('No direct script access.');

class Config {

    private static $instances;
    private $data;

    public static function & instances($id = 0) {

        if (!isset(self::$instances[$id])) {
            $class = __CLASS__;
            self::$instances[$id] = new $class($id);
        }
        return self::$instances[$id];
    }

    public function __construct($id) {

        $this->data = NULL;
        $this->_load($id);
    }

    public function _load($id) {

        if (!$id)
            return FALSE;

        $result = ORM::factory('config')
                ->where('id_config', '=', $id)
                ->find()
                ->as_array();

        $this->data = $result ? $result : array();
    }

    public function get($key = NULL) {

        if (is_null($key)) {
            return $this->data;
        } else {
            return isset($this->data[$key]) ? $this->data[$key] : NULL;
        }
    }

    public function set($data) {

        $config = ORM::factory('config');
        $config->values($data);
        if ($config->check()) {
            $config->save();
            if ($config->saved()) {
                return true;
            }
        }

        return false;
    }

    public function update($data) {
        $config = ORM::factory('config')
                ->where('id_config', '=', $this->data['id_config'])
                ->find();

        if (!$config->loaded()) {
            return false;
        } else {
            $config->values($data);
            if ($config->check()) {
                $config->save();
                if ($config->saved()) {
                    return true;
                }
            }
        }
    }

    public function delete() {
        $config = ORM::factory('config', $this->data['id_config']);
        if ($config->loaded()) {
            return $config->delete();
        } else {
            return FALSE;
        }
    }

    public function get_configs() {
        $cons = ORM::factory('config')->find_all()->as_array();
        if (isset($cons)) {
            foreach ($cons as $key => $value) {
                $configs[$value->fieldname] = $value->value;
            }
            return $configs;
        } else {
            return array();
        }
    }

}

